import Vue from 'vue';
import VueRouter, { RouteConfig } from 'vue-router';

Vue.use(VueRouter);

export const constantRoutes: RouteConfig[] = [
  {
    path: '/home',
    component: () => import('@/views/Home/index.vue')
  }
];

// vue 的路由切换，如果是低版本的路由，那么重复点击切换到相同路由的时侯不会报错，但是如果是最新版本的会报错
const originalPush = VueRouter.prototype.push;
VueRouter.prototype.push = function push(location: any) {
  const t: any = originalPush.call(this, location);
  return t?.catch((err: any) => err);
};

const originalReplace = VueRouter.prototype.replace;
VueRouter.prototype.replace = function replace(location: any) {
  const t: any = originalReplace.call(this, location);
  return t?.catch((err: any) => err);
};

const createRouter = () => {
  return new VueRouter({
    mode: 'history', // Disabled due to Github Pages doesn't support this, enable this if you need.
    scrollBehavior: (to, from, savedPosition) => {
      if (savedPosition) {
        return savedPosition;
      } else {
        return { x: 0, y: 0 };
      }
    },
    base: import.meta.env.BASE_URL,
    routes: constantRoutes
  });
};

const router = createRouter();

// Detail see: https://github.com/vuejs/vue-router/issues/1234#issuecomment-357941465
export function resetRouter() {
  const newRouter = createRouter();
  (router as any).matcher = (newRouter as any).matcher; // reset router
}

export default router;
